import { astUtil, findNodeById } from '@/utils';
import { DeleteFilled, DeleteOutlined, PlusCircleFilled } from '@ant-design/icons';
import { BetaSchemaForm } from '@ant-design/pro-components';
import {
  Alert,
  Button,
  Card,
  Checkbox,
  Collapse,
  Drawer,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Select,
  Space,
} from 'antd';
import CollapsePanel from 'antd/lib/collapse/CollapsePanel';
import { FormInstance } from 'rc-field-form';
import React, { memo, useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import { EventProp } from '../PropsPanel/EventsPanel';
import { columns } from './data';
import FieldItemForm from './FieldItemForm';
import styles from './index.less';

function ProFormPanel({ project, saveNodeChange }: any) {
  const [formList, setFormList] = useState<any[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const baseFormRef = useRef<FormInstance>(null);
  const { ast, currentCompId, pageConfig } = project;
  const currentComponent = findNodeById(pageConfig, currentCompId);
  const currentCompProps = currentComponent?.props ?? {};
  const currentCompEvents = currentComponent?.events ?? {};
  const classProps = astUtil.getClassEventsByAst(ast);
  // console.log(currentComponent);
  const showDrawer = () => setDrawerVisible(true);

  const hideDrawer = () => setDrawerVisible(false);

  const handleSubmit = () => {
    // 保存表单内容

    const baseFormData = baseFormRef.current?.getFieldsValue();
    // 开始修改属性

    if (!currentComponent?.props) currentComponent!.props = {};
    if (!currentComponent?.events) currentComponent!.events = {};

    currentComponent!.props.columns = formList.map((item) => {
      return {
        title: item.title,
        dataIndex: item.dataIndex,
        valueType: item.type,
        valueEnum: item.options,
        formItemProps: {
          tooltip: item.tooltip,
          extra: item.extra,
          initialValue: item.initialValue,
          hasFeedback: item.hasFeedback,
          rules: [
            {
              required: item.required,
              message: item.message,
              // pattern: item.pattern
            },
          ],
        },
      };
    });

    currentComponent!.props.layout = baseFormData.layout || 'horizontal';
    currentComponent!.props.labelCol = { span: baseFormData.labelCol || 4 };
    currentComponent!.props.title = baseFormData.title;
    currentComponent!.events.onFinish = baseFormData.onFinish;
    // 保存节点内容
    saveNodeChange({
      payload: currentComponent,
    });

    // 关闭抽屉
    hideDrawer();
    message.success('保存成功');
  };

  const updateFormData = (formData: any, index: number) => {
    var newFormDataList = formList.concat([]);
    newFormDataList[index] = formData;
    setFormList(newFormDataList);
  };

  const createFormData = () => {
    setFormList(formList.concat({ type: 'input' }));
  };

  /**
   * 删除标单项
   * @param delIndex {number} 被删除的标单项的索引
   */
  const handleDeleteFormItem = (delIndex: number, e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    e.stopPropagation();
    Modal.confirm({
      title: '系统提示',
      content: '确定删除吗?',
      onOk () {
        setFormList(formList.filter((item, index) => index !== delIndex));
        message.success('删除成功');
      }
    });
  };

  useEffect(() => {
    const formData = {
      layout: currentCompProps.layout,
      title: currentCompProps.title,
      labelCol: currentCompProps?.labelCol?.span,
      hasFeedback: currentCompProps?.hasFeedback,
      colon: currentCompProps?.colon,
      onFinish: currentCompEvents?.onFinish,
    };

    baseFormRef.current?.setFieldsValue(formData);
    if (Array.isArray(currentCompProps?.columns)) {
      setFormList(
        currentCompProps?.columns?.map(
          ({ title, dataIndex, valueType, valueEnum, formItemProps }: any) => {
            const {rules, initialValue} = formItemProps || {};
            return {
              title,
              dataIndex,
              initialValue,
              type: valueType,
              tooltip: formItemProps?.tooltip,
              extra: formItemProps?.extra,
              hasFeedback: formItemProps?.hasFeedback,
              required: rules?.length > 0 && rules[1]?.required,
              options: valueEnum
            }
          },
        ) ?? [],
      );
    }
  }, [currentCompProps, currentCompEvents]);

  return (
    <div className={styles.wrap}>
      <div className={styles.cover}>
        <Button type="link" onClick={showDrawer}>
          编辑
        </Button>
      </div>
      <BetaSchemaForm<any>
        columns={columns as any}
        autoFocusFirstInput={false}
        layout="horizontal"
        labelCol={{ span: 4 }}
      />
      <Drawer
        visible={drawerVisible}
        onClose={hideDrawer}
        width={800}
        footer={
          <Space>
            <Button onClick={hideDrawer}>取消</Button>
            <Button type="primary" onClick={handleSubmit}>
              确定
            </Button>
          </Space>
        }
      >
        <Card
          title="基础设置"
          style={{
            background: 'white',
            padding: 10,
            marginBottom: 10,
          }}
        >
          {/* @ts-ignore */}
          <Form labelCol={{ span: 4 }} ref={baseFormRef}>
            <Form.Item label="标题" name="title">
              <Input placeholder="请输入标题" />
            </Form.Item>
            <Form.Item label="布局方式" name="layout" initialValue="horizontal">
              <Select
                options={[
                  {
                    label: '横向布局',
                    value: 'horizontal',
                  },
                  {
                    label: '纵向布局',
                    value: 'vertical',
                  },
                  {
                    label: '行内布局',
                    value: 'inline',
                  },
                ]}
              />
            </Form.Item>
            <Form.Item label="字段名宽度" name="labelCol" initialValue={4}>
              <InputNumber min={0} max={24} step={1} />
            </Form.Item>
            <Form.Item
              label="显示冒号"
              valuePropName="checked"
              name="colon"
              initialValue={true}
            >
              <Checkbox />
            </Form.Item>
            <Form.Item label="提交验证成功" name="onFinish">
              <EventProp name="" event="onFinish" classProps={classProps} />
            </Form.Item>
          </Form>
        </Card>
        <Collapse bordered={false}>
          {formList.map((item, index) => (
            <CollapsePanel
              header={item.title || `字段${index + 1}`}
              extra={<DeleteOutlined onClick={(e) => handleDeleteFormItem(index, e)}/>}
              key={index}
            >
              <FieldItemForm
                initFormData={item}
                onFinish={(data) => updateFormData(data, index)}
              />
            </CollapsePanel>
          ))}
        </Collapse>
        <Button
          type="dashed"
          size="middle"
          style={{ width: '100%', marginTop: 10 }}
          onClick={createFormData}
        >
          <PlusCircleFilled />
          添加字段
        </Button>
      </Drawer>
    </div>
  );
}

const mapStateToProps = ({ project }: any) => ({ project });

const mapDispatchToProps = {
  saveNodeChange: ({ payload }: any) => ({
    type: 'project/saveNodeChange',
    payload,
  }),
};

export default memo(connect(mapStateToProps, mapDispatchToProps)(ProFormPanel));
